//+------------------------------------------------------------------+
//| 断水流指标 - 完整正确版本                                            |
//| 完全复制MT4的6条线 + 箭头显示逻辑                                    |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 11
#property indicator_plots   8

// 6条线 + 2个箭头 = 8个绘图
#property indicator_label1  "Main Line"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrMaroon
#property indicator_width1  3

#property indicator_label2  "Up Line A"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrOrange
#property indicator_width2  3

#property indicator_label3  "Up Line B"
#property indicator_type3   DRAW_LINE
#property indicator_color3  clrOrange
#property indicator_width3  2

#property indicator_label4  "Down Line A"
#property indicator_type4   DRAW_LINE
#property indicator_color4  clrLimeGreen
#property indicator_width4  3

#property indicator_label5  "Down Line B"
#property indicator_type5   DRAW_LINE
#property indicator_color5  clrLimeGreen
#property indicator_width5  3

#property indicator_label6  "Signal Line"
#property indicator_type6   DRAW_LINE
#property indicator_color6  clrMagenta
#property indicator_width6  1

#property indicator_label7  "Up Arrow"
#property indicator_type7   DRAW_ARROW
#property indicator_color7  clrOrange
#property indicator_width7  2

#property indicator_label8  "Down Arrow"
#property indicator_type8   DRAW_ARROW
#property indicator_color8  clrLimeGreen
#property indicator_width8  2

// 输入参数
input int             FastEma     = 13;
input int             SlowEma     = 34;
input int             SignalMA    = 8;
input ENUM_MA_METHOD  SignalMAMode = MODE_EMA;
input int             SigMA       = 8;
input ENUM_MA_METHOD  SigMAMode   = MODE_EMA;
input bool            drawArrows  = true;

// 缓冲区 - 完全对应MT4的结构
double sum[];      // 主基础线（深红色）
double sumua[];    // 上升趋势线A（橙色）
double sumub[];    // 上升趋势线B（橙色）
double sumda[];    // 下降趋势线A（绿色）
double sumdb[];    // 下降趋势线B（绿色）
double sig[];      // 信号线（紫色）
double dotu[];     // 上升箭头
double dotd[];     // 下降箭头

// 计算用缓冲区
double temp1[];
double temp2[];
double state[];

// MA句柄
int fastEmaHandle = INVALID_HANDLE;
int slowEmaHandle = INVALID_HANDLE;
int atrHandle = INVALID_HANDLE;

//+------------------------------------------------------------------+
// MT5版本的MAOnArray函数
double MAOnArray_Fixed(const double &array[], int period, ENUM_MA_METHOD ma_method, int shift)
{
   if(period <= 1 || shift < 0) return 0.0;
   
   int arraySize = ArraySize(array);
   if(shift >= arraySize) return 0.0;
   
   if(shift + period > arraySize) period = arraySize - shift;
   if(period <= 0) return 0.0;
   
   double sum = 0.0;
   
   switch(ma_method)
   {
      case MODE_SMA:
         for(int i = 0; i < period; i++)
         {
            sum += array[shift + i];
         }
         return sum / period;
         
      case MODE_EMA:
         {
            double alpha = 2.0 / (period + 1.0);
            double ema = array[shift];
            for(int i = 1; i < period; i++)
            {
               if(shift + i < arraySize)
                  ema = alpha * array[shift + i] + (1.0 - alpha) * ema;
            }
            return ema;
         }
         
      default:
         for(int i = 0; i < period; i++)
         {
            sum += array[shift + i];
         }
         return sum / period;
   }
}

//+------------------------------------------------------------------+
// MT5版本的PlotPoint函数 - 实现多颜色线条切换
void PlotPoint_Fixed(int i, double &first[], double &second[], double &from[])
{
   if(i < 0 || i >= ArraySize(first) || i >= ArraySize(second) || i >= ArraySize(from))
      return;
   
   // MT4逻辑的MT5版本适配
   bool hasNext1 = (i > 0);
   bool hasNext2 = (i > 1);
   bool hasFromNext = (i > 0);
   
   if (!hasNext1 || first[i - 1] == EMPTY_VALUE)
   {
      if (!hasNext2 || first[i - 2] == EMPTY_VALUE) 
      {
         first[i] = from[i];
         if(hasNext1 && hasFromNext) 
            first[i - 1] = from[i - 1];
         second[i] = EMPTY_VALUE;
      }
      else 
      {
         second[i] = from[i];
         if(hasNext1 && hasFromNext) 
            second[i - 1] = from[i - 1];
         first[i] = EMPTY_VALUE;
      }
   }
   else
   {
      first[i] = from[i];
      second[i] = EMPTY_VALUE;
   }
}

//+------------------------------------------------------------------+
int OnInit()
{
   // 设置缓冲区 - 完全对应MT4结构
   SetIndexBuffer(0, sum, INDICATOR_DATA);      // 主基础线
   SetIndexBuffer(1, sumua, INDICATOR_DATA);    // 上升趋势线A
   SetIndexBuffer(2, sumub, INDICATOR_DATA);    // 上升趋势线B
   SetIndexBuffer(3, sumda, INDICATOR_DATA);    // 下降趋势线A
   SetIndexBuffer(4, sumdb, INDICATOR_DATA);    // 下降趋势线B
   SetIndexBuffer(5, sig, INDICATOR_DATA);      // 信号线
   SetIndexBuffer(6, dotu, INDICATOR_DATA);     // 上升箭头
   SetIndexBuffer(7, dotd, INDICATOR_DATA);     // 下降箭头
   
   // 计算用缓冲区
   SetIndexBuffer(8, temp1, INDICATOR_CALCULATIONS);
   SetIndexBuffer(9, temp2, INDICATOR_CALCULATIONS);
   SetIndexBuffer(10, state, INDICATOR_CALCULATIONS);
   
   // 设置箭头符号
   if(drawArrows) {
      PlotIndexSetInteger(6, PLOT_ARROW, 234);  // MT4的上升箭头符号
      PlotIndexSetInteger(7, PLOT_ARROW, 233);  // MT4的下降箭头符号
   } else {
      PlotIndexSetInteger(6, PLOT_DRAW_TYPE, DRAW_NONE);
      PlotIndexSetInteger(7, PLOT_DRAW_TYPE, DRAW_NONE);
   }
   
   // 创建MA句柄
   fastEmaHandle = iMA(_Symbol, PERIOD_CURRENT, FastEma, 0, MODE_EMA, PRICE_CLOSE);
   slowEmaHandle = iMA(_Symbol, PERIOD_CURRENT, SlowEma, 0, MODE_EMA, PRICE_CLOSE);
   atrHandle = iATR(_Symbol, PERIOD_CURRENT, 20);
   
   if(fastEmaHandle == INVALID_HANDLE || slowEmaHandle == INVALID_HANDLE || atrHandle == INVALID_HANDLE)
   {
      Print("创建指标句柄失败");
      return INIT_FAILED;
   }
   
   return INIT_SUCCEEDED;
}

//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   if(fastEmaHandle != INVALID_HANDLE) IndicatorRelease(fastEmaHandle);
   if(slowEmaHandle != INVALID_HANDLE) IndicatorRelease(slowEmaHandle);
   if(atrHandle != INVALID_HANDLE) IndicatorRelease(atrHandle);
}

//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
{
   if(rates_total < FastEma + SlowEma + SignalMA + SigMA + 10)
      return 0;

   // 检查数据准备情况
   if(BarsCalculated(fastEmaHandle) < rates_total ||
      BarsCalculated(slowEmaHandle) < rates_total ||
      BarsCalculated(atrHandle) < rates_total)
      return prev_calculated;

   // 获取MA数据
   double fastEmaData[], slowEmaData[], atrData[];
   
   int copied1 = CopyBuffer(fastEmaHandle, 0, 0, rates_total, fastEmaData);
   int copied2 = CopyBuffer(slowEmaHandle, 0, 0, rates_total, slowEmaData);
   int copied3 = CopyBuffer(atrHandle, 0, 0, rates_total, atrData);
   
   if(copied1 <= 0 || copied2 <= 0 || copied3 <= 0)
   {
      Print("复制数据失败");
      return prev_calculated;
   }

   // 计算乘数因子
   double Multiply_Factor_1 = 2.0 / (FastEma + 1.0);
   double Multiply_Factor_2 = 2.0 / (SlowEma + 1.0);
   double Multiply_Factor_3 = Multiply_Factor_1 - Multiply_Factor_2;
   if(MathAbs(Multiply_Factor_3) < 1e-10)
   {
      Print("无效的乘数因子");
      return prev_calculated;
   }

   // 计算范围
   int start = prev_calculated == 0 ? 0 : prev_calculated - 1;
   
   // 第一阶段：计算temp1[] - MACD差值
   for(int i = start; i < rates_total; i++)
   {
      temp1[i] = fastEmaData[i] - slowEmaData[i];
   }
   
   // 第二阶段：计算temp2[] - MACD信号线
   for(int i = start; i < rates_total; i++)
   {
      temp2[i] = MAOnArray_Fixed(temp1, SignalMA, SignalMAMode, MathMax(0, i - SignalMA + 1));
   }
   
   // 第三阶段：主循环 - 初始化所有缓冲区
   for(int i = start; i < rates_total; i++)
   {
      // 初始化所有显示缓冲区
      sumua[i] = EMPTY_VALUE;
      sumub[i] = EMPTY_VALUE;
      sumda[i] = EMPTY_VALUE;
      sumdb[i] = EMPTY_VALUE;
      dotu[i] = EMPTY_VALUE;
      dotd[i] = EMPTY_VALUE;
      
      // 计算主基础线（sum[]）
      double sumValue = (Multiply_Factor_1 * fastEmaData[i] + slowEmaData[i] - 
                        fastEmaData[i] - Multiply_Factor_2 * slowEmaData[i] + temp2[i]) / Multiply_Factor_3;
      
      if(!MathIsValidNumber(sumValue))
         sumValue = i > 0 ? sum[i-1] : close[i];
         
      sum[i] = sumValue;
   }
   
   // 第四阶段：信号处理和多颜色线条绘制
   for(int i = start; i < rates_total; i++)
   {
      // 计算信号线
      sig[i] = MAOnArray_Fixed(sum, SigMA, SigMAMode, MathMax(0, i - SigMA + 1));
      
      // 状态判断
      state[i] = 0;
      if(sum[i] > high[i]) state[i] = 1;   // 上升趋势
      if(sum[i] < low[i]) state[i] = -1;   // 下降趋势
      
      // 多颜色线条绘制 - 使用PlotPoint逻辑
      if(state[i] == 1)  PlotPoint_Fixed(i, sumua, sumub, sum);   // 上升：橙色线条
      if(state[i] == -1) PlotPoint_Fixed(i, sumda, sumdb, sum);   // 下降：绿色线条
      
      // 箭头显示
      if(i > 0 && state[i] != state[i-1])
      {
         if(state[i] == 1) 
            dotu[i] = sum[i] + atrData[i] / 2;  // 上升箭头
         if(state[i] == -1) 
            dotd[i] = sum[i] - atrData[i] / 2;  // 下降箭头
      }
   }
   
   // 调试输出
   if(prev_calculated == 0)
   {
      Print("=== 断水流完整版计算完成 ===");
      Print("显示6条线 + 2个箭头，与MT4完全一致");
      for(int j = 0; j < MathMin(3, rates_total); j++)
      {
         Print("[", j, "] sum=", sum[j], " sig=", sig[j], " state=", state[j]);
      }
   }
   
   return rates_total;
}
//+------------------------------------------------------------------+